<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-12-05 18:50:21
 * @Last Modified time: 2022-12-05 19:11:54
 */

namespace addon\qiniu\services;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

// 引入鉴权类
use \Qiniu\Auth;
// 引入上传类
use \Qiniu\Storage\UploadManager;

use frank\exception\CommonException;

/**
 * 七牛云存储支持
 * Class QiniuService
 * @package addon\qiniu\services
 */
class QiniuService 
{
	 /**
     * 设置七牛参数配置
     * @param unknown $filePath 上传图片路径
     * @param unknown $key 上传到七牛后保存的文件名
     */
    public function putFile($param)
    {
        $file_path = $param["file_path"];
        $key       = $param["key"];
        $accessKey = sysconf('qiniu_access_key');
        $secretKey = sysconf('qiniu_secret_key');
        //要上传的空间
        $bucket    = sysconf('qiniu_bucket');
        $domain = sysconf('qiniu_http_domain');
        if(empty($accessKey)){
        	throw new CommonException('七牛云[访问密钥]未配置');
        }
        if(empty($secretKey)){
        	throw new CommonException('七牛云[安全密钥]未配置');
        }
        if(empty($bucket)){
        	throw new CommonException('七牛云[空间名称]未配置');
        }
        if(empty($domain)){
        	throw new CommonException('七牛云[访问域名]未配置');
        }
        $auth      = new Auth($accessKey, $secretKey);
        $token  = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $file_path);
        if ($err !== null) {
			throw new CommonException($err->getResponse()->error);
        } else {
            //返回图片的完整URL
            $domain =  sysconf('qiniu_http')."://".$domain;//自定义域名
            $data   = array(
                "oss_type" => 'qiniu',
                "url" => $domain.'/'.$key,
                "domain" => $domain,
                "path"   => $key,
                "bucket" => $bucket
            );
            return $data;
        }
    }

}